package com.lm56.web;

import com.lm56.common.MyResponseBody;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Kelvin Yeung on 2016/11/24.
 * 需在web.xml配置error-page指向这个controller
 */
@Controller
public class ErrorController {

	/**
	 *返回json
	 * 当request里的header的accept为json，则返回json格式数据
	 */
	@RequestMapping(value = "/error",produces = MediaType.APPLICATION_JSON_UTF8_VALUE )
	@ResponseStatus(code = HttpStatus.OK)
	@ResponseBody
	public MyResponseBody handleJson(HttpServletRequest request){
		Exception ex = (Exception) request.getAttribute("javax.servlet.error.exception");
		if(ex!=null){
			return new MyResponseBody(MyResponseBody.STATUS_ERROR,getErrorMsg(ex));
		}else {
			return new MyResponseBody(MyResponseBody.STATUS_ERROR,"未知错误");
		}
	}


	/**
	 *返回错误页面
	 */
	@RequestMapping(value = "/error" )
	public String handlePage(HttpServletRequest request){
		Exception ex = (Exception) request.getAttribute("javax.servlet.error.exception");
		if(ex!=null){
			request.setAttribute("javax.servlet.error.message",getErrorMsg(ex));
		}
		return "error";
	}


	public String getErrorMsg(Exception ex){
		String errMsg =null;
		String msg = ex.getMessage();
		int idx = msg.indexOf("Exception:");
		try {
			errMsg = msg.substring(idx + 9,msg.length());
		}catch (Exception e){
			e.printStackTrace();
			errMsg = msg;
		}
		return errMsg.trim();
	}

}
